package com.badibadi.activity;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.kxml2.kdom.Document;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.ZoomDensity;
import android.webkit.WebView;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ZoomButtonsController;

import com.badibadi.activity.WebMailActivity.MyRunnable;
import com.badibadi.infos.Results;
import com.badibadi.infos.Web_Content;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.HtmlUtils;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.StringUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.view.my_view.MyWebView_ShowAll;

public class Fingerpost_Activity extends BaseActivity {
	private Button fingerpost_back;
	private TextView fingerpost_tital;
	private WebView fingerpost_content;
	private String panduan_id;
	private Results results;
	private Web_Content web_Content;
	private float width, height;
	private RelativeLayout relative_linshi;
	private boolean hasMeasured = false;
	private MyRunnable r;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(Fingerpost_Activity.this);
				Utils.showMessage(Fingerpost_Activity.this, getResources()
						.getString(R.string.l_net_error));
				break;
			case 2:
				Utils.ExitPrgress(Fingerpost_Activity.this);
				InitData(results.getRetmsg());
				break;
			case 3:
				Utils.ExitPrgress(Fingerpost_Activity.this);
				Utils.showMessage(Fingerpost_Activity.this, getResources()
						.getString(R.string.l_xa10));
				break;
			case 4:
				params();
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.fingerpost_main);
		panduan_id = getIntent().getStringExtra("panduan_id");
		height = getScreenSize(SCREENH);
		fingerpost_back = (Button) findViewById(R.id.fingerpost_back);
		fingerpost_content = (WebView) findViewById(R.id.fingerpost_content);
		relative_linshi = (RelativeLayout) findViewById(R.id.relative_linshi);
		// ViewTreeObserver vto = relative_linshi.getViewTreeObserver();
		// vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
		// public boolean onPreDraw() {
		// if (hasMeasured == false) {
		//
		// // int height = relative_linshi.getMeasuredHeight();
		// width = relative_linshi.getMeasuredWidth();
		// // 获取到宽度后，可用于计算
		// if (width != 0) {
		// handler.sendEmptyMessage(4);
		// hasMeasured = true;
		// }
		//
		// }
		// return true;
		// }
		// });
		fingerpost_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		fingerpost_tital = (TextView) findViewById(R.id.fingerpost_tital);
		if (panduan_id.equals("feedback")) {// 意见反馈
			fingerpost_tital.setText(getResources()
					.getString(R.string.Feedback));
		} else if (panduan_id.equals("Maps")) {// 使用帮助
			fingerpost_tital.setText(getResources().getString(
					R.string.UserTheHelp));
		} else if (panduan_id.equals("aboutUs")) {// 关于我们
			fingerpost_tital
					.setText(getResources().getString(R.string.AboutUs));
		} else if (panduan_id.equals("statement")) {// 隐私申明
			fingerpost_tital.setText(getResources().getString(
					R.string.PrivacyStatement));
		}
		params();
	}

	private void InitData(String url) {
		//    
		// fingerpost_content.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		// WebSettings webSettings = fingerpost_content.getSettings();
		// webSettings.setJavaScriptEnabled(false);
		// webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);//
		// (根据图片大小自适应webview的大小)
		// // webSettings.setBuiltInZoomControls(true);//万恶的放大缩小按钮（不建议显示）
		// setZoomControlGone(fingerpost_content);
		// fingerpost_content.getSettings().setDefaultTextEncodingName("UTF-8");
		// fingerpost_content.loadData(
		// Is_Tu(web_Content.getContents(), (int) width-400,
		// ((int) width) - 450), "text/html;charset=UTF-8", null);
		fingerpost_content.getSettings().setLayoutAlgorithm(
				LayoutAlgorithm.SINGLE_COLUMN);

		// journey_details_webView.loadUrl(west.getContent() + "");
		fingerpost_content.getSettings().setJavaScriptEnabled(true);
		fingerpost_content.getSettings().setDomStorageEnabled(true);
		fingerpost_content.getSettings().setUseWideViewPort(true);
		fingerpost_content.getSettings().setLoadWithOverviewMode(true);

		fingerpost_content.getSettings().setBuiltInZoomControls(false);// 会出现放大缩小的按钮

		//    ("========"+west.getContent());
		// journey_details_webView.loadUrl(west.getContent());
		//    
		// journey_details_webView.setWebViewClient(new MyWebViewClient());
		fingerpost_content.loadUrl(url);
		fingerpost_content.setWebViewClient(new myWebViewClient());
		// fingerpost_content.setOnTouchListener(new OnTouchListener() {
		// private float OldX1, OldY1, OldX2, OldY2;
		// private float NewX1, NewY1, NewX2, NewY2;
		//
		// @Override
		// public boolean onTouch(View v, MotionEvent event) {
		// // TODO Auto-generated method stub
		// switch (event.getAction()) {
		// case MotionEvent.ACTION_POINTER_2_DOWN:
		// if (event.getPointerCount() == 2) {
		// OldX1 = event.getX(0);
		// OldY1 = event.getY(0);
		// OldX2 = event.getX(1);
		// OldY2 = event.getY(1);
		// }
		// break;
		// case MotionEvent.ACTION_MOVE:
		// if (event.getPointerCount() == 2) {
		// if (OldX1 == -1 && OldX2 == -1)
		// break;
		// NewX1 = event.getX(0);
		// NewY1 = event.getY(0);
		// NewX2 = event.getX(1);
		// NewY2 = event.getY(1);
		// float disOld = (float) Math.sqrt((Math.pow(OldX2
		// - OldX1, 2) + Math.pow(OldY2 - OldY1, 2)));
		// float disNew = (float) Math.sqrt((Math.pow(NewX2
		// - NewX1, 2) + Math.pow(NewY2 - NewY1, 2)));
		//    
		// + disNew);
		// if (disOld - disNew >= 25) {
		// // 缩小
		// fingerpost_content.zoomOut();
		// // holder.introduce.loadUrl("javascript:mapScale=1;");
		//    
		// } else if (disNew - disOld >= 25) {
		// // 放大
		// fingerpost_content.zoomIn();
		// // holder.introduce.loadUrl("javascript:mapScale=-1;");
		//    
		// }
		// OldX1 = NewX1;
		// OldX2 = NewX2;
		// OldY1 = NewY1;
		// OldY2 = NewY2;
		// }
		// break;
		// case MotionEvent.ACTION_UP:
		// if (event.getPointerCount() < 2) {
		// OldX1 = -1;
		// OldY1 = -1;
		// OldX2 = -1;
		// OldY2 = -1;
		// }
		// break;
		// }
		// return false;
		// }
		// });
	}

	private class myWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// TODO Auto-generated method stub
			return super.shouldOverrideUrlLoading(view, url);
		}

	}

	public void setZoomControlGone(View view) {
		Class classType;
		Field field;
		try {
			classType = WebView.class;
			field = classType.getDeclaredField("mZoomButtonsController");
			field.setAccessible(true);
			ZoomButtonsController mZoomButtonsController = new ZoomButtonsController(
					view);
			mZoomButtonsController.getZoomControls().setVisibility(View.GONE);
			try {
				field.set(view, mZoomButtonsController);
			} catch (IllegalArgumentException e) {
				   
			} catch (IllegalAccessException e) {
				   
			}
		} catch (SecurityException e) {
			   
		} catch (NoSuchFieldException e) {
			   
		}
	}

	/**
	 * 返回网页数据中是否有图片数据，有的话进行处理
	 * 
	 * @param d
	 * @return
	 */
	private String Is_Tu(String d, int w, int h) {
		if (d != null) {
			String dd1[] = d.split("src=\"");
			if (dd1 != null && dd1.length > 1) {
				// String fanhui = "";
				for (int i = 1; i < dd1.length; i++) {
					String dd2[] = dd1[i].split("\" alt");
					if (dd2 != null && dd2.length > 0) {
						if (Is_Biaoqing(dd2[0])) {
							d = d.replace(dd2[0], Constants.BadiWebImgUrl
									+ dd2[0] + "\" style=\"width:" + w
									+ "px; height:" + h + "px;");
						}
					}
				}
//				   
				return d;
			} else {
//				   
				return d;
			}
		} else {
			return "";
		}
	}

	/**
	 * 判断图片是否是表情
	 * 
	 * @param d
	 * @return
	 */
	private boolean Is_Biaoqing(String d) {

		String string = d;
		String sub = "http://";
		int a = string.indexOf(sub);
		if (a >= 0) {
			return false;
		} else {
			return true;
		}
	}

	private void params() {
		Utils.showPrgress(Fingerpost_Activity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				web_Content = new Web_Content();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("type", panduan_id);
//				   
				String content = Utils.sendRequest(map, Constants.BadiUrl_1
						+ "web/appwebinfo");
				if (content != null) {
					results = Utils.checkResult_NNN(getApplicationContext(),
							content);
//					   
					if (results != null && !results.getRetmsg().equals("null")
							&& results.isRet()) {
						// try {
						// web_Content = JSONUtils.getEntityByJsonString(
						// results.getRetmsg(), Web_Content.class);
						handler.sendEmptyMessage(2);
						// } catch (Exception e) {
						// // TODO Auto-generated catch block
						//    
						// }
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}
}
